import React, { useState, useEffect } from 'react'
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { Layout, Menu, Badge, Avatar } from 'antd';
import { ContactsOutlined, HomeOutlined, ProjectOutlined, AppstoreOutlined, BellOutlined } from '@ant-design/icons';
import styles from './App.module.css';
import axios from 'axios';
import { Dropdown, } from 'antd';

const { Header, Sider, Content } = Layout;
function traverseMenus(menus) {
  menus.forEach(menu => {
    console.log(menu.key, menu.title);
    if (menu.children && menu.children.length > 0) {
      traverseMenus(menu.children);
    }
  });
}

// 用法

export default function App() {
  const [menuItems,setmenuItems] = useState([]);
  const navigate = useNavigate();
  const location = useLocation();
  const [openKeys, setOpenKeys] = useState([]);
    // 选中当前路由
  const selectedKeys = [location.pathname];
// 处理menuItems数据
  function processMenuItems(items, navigate) {
    return items.map(item => {
      let newItem = { ...item };

      // 递归处理 children
      if (newItem.children && newItem.children.length > 0) {
        newItem.children = processMenuItems(newItem.children, navigate);
      } else {
        // 没有 children 或 children 为空，删除 children 属性并加 onClick
        delete newItem.children;
        newItem.onClick = () => navigate(newItem.key);
      }

      return newItem;
    });
  }


  // 可选：自动展开父级菜单
  useEffect(() => {
    // 假设你的菜单 key 结构是 /dashboard/userlist 这种
    const paths = location.pathname.split('/').filter(Boolean);
    if (paths.length > 1) {
      // 展开所有父级
      const keys = [];
      for (let i = 1; i < paths.length; i++) {
        keys.push('/' + paths.slice(0, i).join('/'));
      }
      setOpenKeys(keys);
    } else {
      setOpenKeys([]);
    }
    
  }, [location.pathname]);

  // 处理menuItems数据
  function processMenuItems(items, navigate) {
    // 先对本层 items 按 order 降序排序
    const sortedItems = [...items].sort((a, b) => (Number(a.order) || 0) - (Number(b.order) || 0));
    return sortedItems.map(item => {
      let newItem = { ...item };

      // 递归处理 children
      if (newItem.children && newItem.children.length > 0) {
        newItem.children = processMenuItems(newItem.children, navigate);
      } else {
        // 没有 children 或 children 为空，删除 children 属性并加 onClick
        delete newItem.children;
        newItem.onClick = () => navigate(newItem.key);
      }
      
      return newItem;
    });
  }

  useEffect(()=>{
    const userId = sessionStorage.getItem('userId');
    if (!userId) return;
    axios.get(`http://localhost:3000/getUserTree?userId=${userId}`).then(res=>{
      const processed = processMenuItems(res.data.data, navigate);
      setmenuItems(processed)
    })
    
  },[])
  // const menuItems = [
  //   {
  //     key: 'shou',
  //     icon: <HomeOutlined />,
  //     label: '首页',
  //     onClick: () => navigate('/shou')
  //   },
  //   {
  //     key: 'dashboard',
  //     icon: <ContactsOutlined />,
  //     label: '权限管理',
  //     children: [
  //       {
  //         key: 'userlist',
  //         label: '用户列表',
  //         onClick: () => navigate('/dashboard/userlist')
  //       },
  //       {
  //         key: 'rolelist',
  //         label: '角色列表',
  //         onClick: () => navigate('/dashboard/rolelist')
  //       },
  //       {
  //         key: 'menulist',
  //         label: '菜单列表',
  //         onClick: () => navigate('/dashboard/menulist')
  //       },
  //     ],
  //   },
  //   {
  //     key: 'project',
  //     icon: <ProjectOutlined />,
  //     label: '项目管理',
  //     children: [
  //       {
  //         key: 'work',
  //         icon: <AppstoreOutlined />,
  //         label: '工作台',
  //         onClick: () => navigate('/work')
  //       },
  //       {
  //         key: 'projectlist',
  //         label: '项目列表',
  //         onClick: () => navigate('/projects/projectlist')
  //       },
  //       {
  //         key: 'aftersales',
  //         label: '售后需求记录',
  //         onClick: () => navigate('/projects/aftersales')
  //       },
  //       {
  //         key: 'aftersaleslist',
  //         label: '售后需求列表',
  //         onClick: () => navigate('/projects/aftersaleslist')
  //       },
  //       {
  //         key: 'correspondence',
  //         label: '项目函件列表',
  //         onClick: () => navigate('/projects/correspondence')
  //       },
  //       {
  //         key: 'phases',
  //         label: '项目阶段列表',
  //         onClick: () => navigate('/projects/phases')
  //       },
  //       {
  //         key: 'tasks',
  //         label: '项目任务列表',
  //         onClick: () => navigate('/projects/tasks')
  //       },
  //       {
  //         key: 'attachments',
  //         label: '项目附件',
  //         onClick: () => navigate('/projects/attachments')
  //       },
  //       {
  //         key: 'meetingnotes',
  //         label: '项目会议记要',
  //         onClick: () => navigate('/projects/meetingnotes')
  //       }
  //     ],
  //   },
  //   {
  //     key: 'performance',
  //     label: '员工绩效管理',
  //     onClick: () => navigate('/performance')
  //   },
  //   {
  //     key: 'suppliers',
  //     label: '分包供应商',
  //     onClick: () => navigate('/suppliers')
  //   },
  //   {
  //     key: 'messages',
  //     label: '消息-项目消息',
  //     onClick: () => navigate('/messages')
  //   },
  //   {
  //     key: 'system',
  //     label: '系统设置',
  //     children: [
  //       {
  //         key: 'settings',
  //         label: '项目信息配置',
  //         onClick: () => navigate('/system/settings')
  //       }


  //     ],
  //   },

  // ];
  const userMenu = {
    items: [
      { key: 'profile', label: '个人主页', onClick: () => navigate('/profile') },
      { key: 'settings', label: '设置', onClick: () => navigate('/system/settings') },
      { type: 'divider' },
      {
        key: 'logout', label: '退出', onClick: () => {
          sessionStorage.clear();
          navigate('/login');
        }
      },
    ]
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{
        background: '#001529',
        padding: '0 20px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        color: 'white'
      }} className={styles.header}>
        <div className={styles.logo} style={{ fontSize: '18px', fontWeight: 'bold', color: 'white' }}>
          项目管理系统
        </div>
        <div className={styles.headerRight}>
          <Badge count={5}>
            <BellOutlined style={{ fontSize: '18px', color: 'white' }} />
          </Badge>
          <Badge count={3}>
            <span style={{ fontSize: '14px', color: 'white' }}>审批</span>
          </Badge>
          <Dropdown menu={userMenu} trigger={['click']} placement="bottomRight" arrow>
            <Avatar style={{ backgroundColor: '#87d068', cursor: 'pointer' }}>用户</Avatar>
          </Dropdown>
        </div>
      </Header>
      <Layout>
        <Sider width={200} className={styles.sider} theme="dark">
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            openKeys={openKeys}
            onOpenChange={setOpenKeys}
            style={{ height: '100%', borderRight: 0 }}
            items={menuItems}
            theme="dark"
          />
        </Sider>
        <Content className={styles.content}>
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  )
}
